package com.leezk.order.utils;

import com.sun.org.apache.xpath.internal.operations.Bool;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Random;
import java.util.UUID;

/**
 * @Author: 小童
 * @CreateDate: 2021/7/22 0:10
 * @note:
 * @Version: 1.0
 */
public class StringUtil {

    public static String getRandomString(int length){

        //1. 定义一个字符串（A-Z，a-z，0-9）即62个数字字母；
        String str="zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        //2. 由Random生成随机数
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        //3. 长度为几就循环几次
        for(int i=0; i<length; ++i){
            //从62个的数字或字母中选择
            int number=random.nextInt(62);
            //将产生的数字通过length次承载到sb中
            sb.append(str.charAt(number));
        }
        //将承载的字符转换成字符串
        return sb.toString();
    }

    public static String  createToken() {
        String token="token:"+getRandomString(32);
        BASE64Encoder encoder = new BASE64Encoder();
        try {
            return encoder.encode(token.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "token:aadadaauiufufafau11111";
    }

    public static Boolean checkToken(String token) {
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] bytes = new byte[0];
        try {
            bytes = decoder.decodeBuffer(token);
            String s = new String(bytes, "UTF-8");
            if (s.startsWith("token:")){
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 根据UUID生成订单号
     * @return
     */
    public static String getOrderIdByUUId()
    {
        int value = UUID.randomUUID().toString().hashCode();
        if (value < 0) {
            value = -value;
        }
        //0代表前面补充0，10代表长度，d代表正整数
        return String.format("%010d", value);
    }

}
